<?php

namespace App\Containers\AppSection\Profile\Actions;

use App\Containers\AppSection\Accreditation\Actions\SendToAccreditationSubAction;
use App\Containers\AppSection\Confirmation\Tasks\DeleteAllConfirmsByValueTask;
use App\Containers\AppSection\Confirmation\Tasks\FindConfirmationByCodeTask;
use App\Containers\AppSection\Data\Tasks\UpdateCompanyTask;
use App\Containers\AppSection\Data\Tasks\UpdatePassportTask;
use App\Containers\AppSection\Data\Tasks\UpdatePersonalTask;
use App\Containers\AppSection\LegalForm\Tasks\UpdateLegalFormTask;
use App\Containers\AppSection\Log\Tasks\CreateLogTask;
use App\Containers\AppSection\Profile\Tasks\ChangeProfilePhoneTask;
use App\Containers\AppSection\Profile\Tasks\FindProfileByIdTask;
use App\Containers\AppSection\Profile\Tasks\UpdateProfileTask;
use App\Containers\AppSection\Questionnaire\SubActions\UpdateResponseSubAction;
use App\Ship\Parents\Actions\Action;
use App\Ship\Parents\Requests\Request;

class UpdateOuterProfileAction extends Action
{
    public function run(Request $request)
    {
        //Валидация кода, отправленного на телефон
        if (!empty($request->getInputByKey('personal.phone_code'))) {
            //Поиск кода
            app(FindConfirmationByCodeTask::class)->run(
                $request->getInputByKey('personal.phone_code'), $request->getInputByKey('personal.phone'),
                config('appSection-confirmation.confirms.phone.requests.register'),
                config('appSection-confirmation.confirms.phone.type')
            );

            //Смена телефона
            app(ChangeProfilePhoneTask::class)->run($request->profile()->id, $request->getInputByKey('personal.phone'));
        }

        $profile = app(FindProfileByIdTask::class)->run($request->profile()->id);

        $personalData = $request->sanitizeInput([
            'personal.fio',
            'personal.without_patronymic',
            'personal.birth_date',
            'personal.ogrnip',
            'personal.inn',
            'personal.birth_place',
            'personal.registration_address',
            'personal.address_matches',
            'personal.residence_address',
        ]);
        //Обновление персональных данных
        app(UpdatePersonalTask::class)->run($profile->legal_form->personal->id, $personalData["personal"]);

        $passportData = $request->sanitizeInput([
            'passport.serial_number',
            'passport.issue_date',
            'passport.department_code',
            'passport.issued_by',
            'passport.first_photo_id',
            'passport.second_photo_id',
        ]);
        //Обновление персональных данных
        app(UpdatePassportTask::class)->run($profile->legal_form->passport->id, $passportData["passport"]);

        //Обновление документов
        if ($profile->hasLegalForm('entity')) {
            app(UpdateLegalFormTask::class)->run($profile->legal_form->id, ['documents' => $request->input('documents', [])]);
        }

        //Обновление данных компании
        if ($profile->hasLegalForm('entity')) {
            $companyData = $request->sanitizeInput([
                'company.name',
                'company.ogrn',
                'company.inn',
                'company.legal_address',
                'company.actual_address',
                'company.address_matches',
            ]);

            app(UpdateCompanyTask::class)->run($profile->legal_form->company->id, $companyData["company"]);
        }

        foreach ($request->getInputByKey('responses') as $response) {
            app(UpdateResponseSubAction::class)->run($response['id'], $response['values']);
        }

        //Удаление отправленных кодов на телефон
        app(DeleteAllConfirmsByValueTask::class)
            ->run($request->getInputByKey('personal.phone'), config('appSection-confirmation.confirms.phone.requests.register'), config('appSection-confirmation.confirms.phone.type'));

        app(CreateLogTask::class)->run($request->profile()->id, 'Редактирование данных профиля', 'profile');

        //Отправка на аккредитацию
        if (!$request->getInputByKey('is_draft', false)) {
            app(SendToAccreditationSubAction::class)->run($request->profile()->id);
        }else{
            app(UpdateProfileTask::class)
                ->run($request->profile()->id, [
                    'accreditation_status_key' => 'accreditation_not_accredited',
                    'accredited_at' => null
                ]);
        }
    }
}
